<template>
  <div class="comment_send">
    <div class="user_face">
      <div class="avatar">
        <img :src="comObj.avatar" alt="头像" class="avatar_img" />
      </div>
      <div class="avatar_pendent">
        <img
          class="avatar_outer_img"
          :src="comObj.avatar_pendent"
          alt="头像框"
        />
      </div>
      <span class="avatar_icon"></span>
    </div>
    <div class="textarea_container">
      <div
        class="ipt_txt"
        :class="[
          textContent ? '' : 'placeholder-shown',
          inptxt_focus ? 'focus' : '',
        ]"
        :placeholder="placeholder"
      >
        <div
          contenteditable="true"
          id="editor"
          class="inputbox"
          @focus="inp_focus(comObj)"
          @blur="inp_blur(comObj)"
          @input="inp_input(comObj)"
          :ref="`inputbox`"
        ></div>
      </div>
      <button
        type="submit"
        class="comment_submit"
        @click="commentSubmit(comObj)"
      >
        发表评论
      </button>
    </div>
    <div class="comment_emoji" @click.stop="openEmojiBox($event)">
      <i class="icon"></i>
      <span class="text">表情</span>
    </div>
    <div class="dynamic_repost" @click="commentRepost()" v-if="allowRepost">
      <label>
        <div
          class="checkbox"
          :class="commentRepostActive ? 'active' : ''"
        ></div>
        <span>同时转发到我的动态</span>
      </label>
    </div>
  </div>
</template>

<script>
import EMOJILIST from "../../static/emoji.js";
export default {
  data() {
    return {
      $inputbox: null, //输入框对象
      inptxt_focus: false, //输入框聚焦
      textContent: "", //输入框内容
      commentRepostActive: false, //勾选转发
      emojiList: EMOJILIST,
    };
  },
  props: {
    comObj: {
      typeof: Object,
      required: false,
    },
    allowRepost: {
      typeof: Boolean,
      required: false,
      default: false,
    },
    placeholder: {
      typeof: String,
      required: false,
      default: "发一条友善的评论",
    },
  },
  mounted() {
    // console.log(this.comObj);
    this.$nextTick(() => {
      this.$inputbox = this.$refs.inputbox;
    });
  },
  methods: {
    //   输入框聚焦
    inp_focus() {
      this.inptxt_focus = true;
      this.$nextTick(() => {
        this.$bus.$emit("getNode", this.$inputbox);
      });
      this.$bus.$on("inputEmoji", (data) => {
        this.inputEmoji(data);
      });
    },
    // 输入框失焦
    inp_blur() {
      this.inptxt_focus = false;
      this.$bus.$off("inputEmoji");
    },
    // 输入框输入
    inp_input() {
      //开始输入换行导致内容计数出错
      if (/^\n\n/.test(this.$inputbox.innerHTML)) {
        this.$inputbox.innerHTML = "";
        this.$inputbox.normalize();
        return;
      }
      this.$set(this, "textContent", this.$inputbox.textContent);
      this.$inputbox.normalize();
    },
    // 设置光标位置
    setRange(node, offset) {
      let range = document.createRange();
      range.selectNodeContents(node);
      range.setStart(node, offset);
      range.setEnd(node, offset);
      range.collapse(false);
      let sel = getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    },
    // 插入表情
    inputEmoji(emoji) {
      let range = getSelection().getRangeAt(0);
      let { startOffset, endOffset, commonAncestorContainer } = range;
      let text = emoji.title ? emoji.title : emoji.text;
      let textNode = document.createTextNode(text);
      if (startOffset == endOffset) {
        range.insertNode(textNode);
        range.collapse(false);
      } else {
        let startText = this.textContent.slice(0, startOffset);
        let endText = this.textContent.slice(endOffset);
        let startNode = document.createTextNode(startText);
        let endNode = document.createTextNode(endText);
        let docF = document.createDocumentFragment();
        docF.appendChild(startNode);
        docF.appendChild(textNode);
        docF.appendChild(endNode);
        commonAncestorContainer.parentNode.replaceChild(
          docF,
          commonAncestorContainer
        );
        this.setRange(endNode, 0);
      }
      this.inp_input();
    },
    // 清除文本框内容
    inp_clear() {
      this.$inputbox.innerHTML = "";
      this.$inputbox.normalize();
      this.$set(this, "textContent", "");
    },
    // 发表评论
    commentSubmit() {
      // 进行表情转译
      if (!this.textContent) return;
      let emojiReg = new RegExp(/(\[[\u4e00-\u9fa5a-zA-Z0-9_]+\])+?/g);
      if (this.textContent.search(emojiReg) >= 0) {
        let arr = this.textContent.split(emojiReg);
        let textContentArr = [];
        arr.forEach((item) => {
          if (item != "") {
            textContentArr.push(this.transEmoji(item));
          }
        });
        this.textContent = textContentArr.join("");
      }
      if (this.commentRepostActive) {
        // 评论并转发
      } else {
        // 评论
      }
      this.inp_clear();
      this.$set(this, "commentRepostActive", false);
    },
    // 格式时间
    getTime() {
      let date = new Date();
      const YEAR = date.getFullYear();
      const MONTH = date.getMonth() + 1;
      const DAY = date.getDate();
      const HOUR = date.getHours();
      const MIN = date.getMinutes();
      const SEC = date.getSeconds();
      return `${YEAR}-${MONTH}-${DAY} ${HOUR}:${MIN}:${SEC}`;
    },
    // 文本转表情
    transEmoji(text) {
      if (!text) return;
      for (let [i, emojiItem] of Object.entries(this.emojiList)) {
        if (emojiItem.pid) {
          for (let [j, emoji] of Object.entries(emojiItem.emojis)) {
            if (emoji.title == text) {
              let docF = document.createElement("div");
              let expression = document.createElement("img");
              expression.src = emoji.imgUrl;
              expression.alt = emoji.title;
              expression.style.margin = `-1px 1px 0px`;
              expression.style.display = `inline-block`;
              expression.style.width = `20px`;
              expression.style.height = `20px`;
              expression.style["vertical-align"] = `text-bottom`;
              docF.appendChild(expression);
              return docF.innerHTML;
            }
          }
        }
      }
      return text;
    },
    // 打开表情
    openEmojiBox($event) {
      let left = 0;
      let top = 0;
      if (this.$el.offsetParent.className !== "panel_area") {
        let parent = this.$el.offsetParent;
        left =
          $event.currentTarget.offsetLeft +
          this.$el.offsetLeft +
          parent.offsetLeft;
        top = this.$el.offsetTop + this.$el.offsetHeight + parent.offsetTop;
      } else {
        left = $event.currentTarget.offsetLeft + this.$el.offsetLeft;
        top = this.$el.offsetTop + this.$el.offsetHeight;
      }
      if (!this.$inputbox) return;
      this.$inputbox.focus();
      this.$emit("openEmojiBox");
      this.$nextTick(() => {
        this.$bus.$emit("getPosition", top, left);
      });
      this.documentCB("click", () => {
        this.$emit("hiddenEmojiBox");
      });
    },
    // 监听页面事件回调
    documentCB(eventType, fn) {
      let CB = () => {
        fn();
        document.removeEventListener(eventType, CB);
      };
      document.addEventListener(eventType, CB);
    },
    // 勾选转发
    commentRepost() {
      if (this.commentRepostActive) {
        this.$set(this, "commentRepostActive", false);
      } else {
        this.$set(this, "commentRepostActive", true);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.comment_send {
  padding-top: 15px;
  margin: 10px 0;
  position: relative;
  .user_face {
    width: 72px;
    height: 72px;
    position: absolute;
    .avatar {
      position: absolute;
      overflow: hidden;
      top: 16px;
      left: 16px;
      z-index: 1;
      img {
        border-radius: 50%;
        width: 40px;
        height: 40px;
      }
    }
    .avatar_pendent {
      position: absolute;
      overflow: hidden;
      z-index: 2;
      img {
        width: 72px;
        height: 72px;
      }
    }
  }
  .textarea_container {
    margin-left: 85px;
    margin-right: 80px;
    position: relative;
    .ipt_txt {
      vertical-align: top;
      font-size: 12px;
      color: #555;
      box-sizing: border-box;
      border: 1px solid #e5e9ef;
      background-color: #f4f5f7;
      padding: 5px 10px;
      outline: none;
      height: 65px;
      width: 100%;
      display: inline-block;
      border-radius: 4px;
      &.placeholder-shown::before {
        content: attr(placeholder);
        position: absolute;
        top: 5px;
        left: 10px;
      }
      .inputbox {
        position: relative;
        width: 100%;
        top: 0;
        left: 0;
        color: #222;
        -webkit-user-modify: read-write-plaintext-only;
        font-size: 12px;
        font-family: Helvetica Neue, Helvetica, Arial, Microsoft Yahei,
          Hiragino Sans GB, Heiti SC, WenQuanYi Micro Hei, sans-serif;
        min-height: 44px;
        vertical-align: baseline; //文字对齐
        word-break: break-word;
        word-wrap: break-word;
        height: 50px;
        overflow: auto;
        &:focus {
          outline: none;
        }
      }
      &.focus {
        background-color: #fff;
        border: 1px solid #00a1d6;
      }
      &:hover {
        background-color: #fff;
        border: 1px solid #00a1d6;
      }
    }
    .comment_submit {
      padding: 4px 15px;
      padding-top:10px;
      width: 70px;
      height: 64px;
      border-radius: 4px;
      background-color: #00a1d6;
      cursor: pointer;
      text-align: center;
      font-size: 14px;
      line-height: unset;
      color: #fff;
      vertical-align: top;
      user-select: none;
      position: absolute;
      top: 0;
      right: -80px;
      &:hover {
        background-color: #00b5e5;

      }
    }
  }
  .comment_emoji {
    margin-left: 85px;
    display: inline-block;
    font-size: 12px;
    color: #99a2aa;
    width: 66px;
    height: 24px;
    line-height: 23px;
    background-color: #fff;
    box-shadow: 0 1px 10px 0 rgba(106, 115, 133, 0.25);
    text-align: center;
    border-radius: 4px;
    cursor: pointer;
    &:hover {
      color: #555;
    }
  }
  .dynamic_repost {
    display: inline-block;
    margin-left: 15px;
    font-size: 12px;
    color: #99a2aa;
    .checkbox {
      width: 12px;
      height: 12px;
      display: inline-block;
      border: 1px solid #555;
      border-radius: 2px;
      margin: 0px 2px 0 0;
      transform: translateY(2px);
      &.active {
        background-color: #555;
        &::after {
          content: "✔";
          font-size: 12px;
          font-weight: bold;
          color: #fff;
          position: relative;
          top: -3px;
        }
      }
    }
  }
}
</style>